package httpService

import (
	"context"
	"encoding/json"
	"github.com/labstack/echo/v4"
	"github.com/smallnest/rpcx/client"
	"github.com/smallnest/rpcx/protocol"
	"os"
	"pm/config"
	"pm/rpc"
	"strconv"
)

func ProcessLogFile(c echo.Context)error {
	server := c.FormValue("server")
	if server != ""{
		d, _ := client.NewPeer2PeerDiscovery(server+":"+strconv.Itoa(rpc.Port), "")
		opt := client.DefaultOption
		opt.SerializeType = protocol.JSON
		var reply rpc.DataOutput
		xclient := client.NewXClient(rpc.ServerName, client.Failtry, client.RandomSelect, d, opt)
		err := xclient.Call(context.Background(), "log.files", "{}", &reply)
		if err != nil{
			return c.JSON(200, map[string]interface{}{
				"status": 1,
				"msg":err.Error(),
			})
		}else{
			if reply.Message != nil{
				return c.JSON(200, map[string]interface{}{
					"status": 1,
					"msg":reply.Message,
				})
			}
			var list []string
			json.Unmarshal([]byte(reply.Body.(string)), &list)
			return c.JSON(200, map[string]interface{}{
				"status": 0,
				"data":list,
			})
		}
	}
	file, _ := os.Open(config.ConfigData.Logs)
	files, err := file.ReadDir(-1)

	if err != nil {
		return c.JSON(200, map[string]interface{}{
			"status": 0,
			"data":[]string{},
		})
	}
	filesData := make([]string, 0)
	for _, item := range files {
		filesData = append(filesData, item.Name())
	}

		return c.JSON(200, map[string]interface{}{
			"status": 0,
			"data":filesData,
		})

}
